<?php


namespace EchoPHP\Http\Middleware;

use Closure;
use EchoPHP\Facades\Log;
use EchoPHP\Foundation\Exception\HttpException;
use EchoPHP\Http\Request;
use EchoPHP\Http\Response;

class EnableCrossMiddle {

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle($request, Closure $next) {
        $crosOptions = config('cros', []);
        if (isset($crosOptions['enable_cros']) && $crosOptions['enable_cros'] === true && isset($crosOptions['allow_origin']) && !empty($crosOptions['allow_origin'])) {
            $origin = $request->server()->get('HTTP_ORIGIN') ? $request->server()->get('HTTP_ORIGIN') : '';

            if (in_array($origin, $crosOptions['allow_origin']) || in_array('*', $crosOptions['allow_origin'])) {
                app()->addGlobalHeaders('Access-Control-Allow-Origin', $origin);
                app()->addGlobalHeaders('Access-Control-Allow-Headers', $crosOptions['allow_headers']);
                app()->addGlobalHeaders('Access-Control-Expose-Headers', $crosOptions['expose_headers']);
                app()->addGlobalHeaders('Access-Control-Allow-Methods', $crosOptions['allow_methods']);
                app()->addGlobalHeaders('Access-Control-Allow-Credentials', $crosOptions['allow_credentials']);

                if ($request->getMethod() == 'OPTIONS') {
                    app()->addGlobalHeaders('Access-Control-Max-Age', 1728000);
                    app()->addGlobalHeaders('Content-Type', 'text/plain; charset=utf-8');
                    app()->addGlobalHeaders('Content-Length', 0);
                    return new Response('', 200);
                }
            }
        }
        $response = $next($request);
        return $response;
    }
}